package com.hnkywl.jip.dao;

import net.ruixin.orm.hibernate.Page;
import net.ruixin.orm.hibernate.SimpleHibernateTemplate;
import org.hibernate.SQLQuery;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 说明：
 * 包:        com.hnkywl.jip.dao
 * 类描述:    供应商
 * 创建人:    ZHUCHG
 * 创建时间: 13-2-28 下午8:35
 * 修改人:    ZHUCHG
 * 修改时间: 13-2-28 下午8:35
 * 修改备注: [说明本次修改内容]
 * 版本:        [v1.0]
 */
@Repository
public class SupplierDao extends SimpleHibernateTemplate {
    public Page<Object[]> findSupplier(Integer companyId, Integer supplierId, String code, Integer limit, Integer start) {
        String sqlColumn = "select company_id,dbo.gf_compid_shortname(company_id) as company_name," +
                " supplier_id,dbo.gf_custid_fullname(supplier_id) as supplier_name,code " +
                " from t_jiuqi_supplier_mapping ";
        String sqlCount = "select count(1) from t_jiuqi_supplier_mapping ";

        String sqlCondition = "  where status=1 ";
        if (companyId != null)
            sqlCondition += " and company_id=:company_id ";
        if (supplierId != null)
            sqlCondition += " and supplier_id=:supplier_id ";
        if (code != null)
            sqlCondition += " and code like :code ";

        SQLQuery query = createSQLQuery(sqlCount + sqlCondition);
        if (companyId != null)
            query.setInteger("company_id", companyId);
        if (supplierId != null)
            query.setInteger("supplier_id", supplierId);
        if (code != null)
            query.setString("code", "%" + code + "%");
        Integer total = (Integer) query.uniqueResult();
        List<Object[]> result = null;
        if (total > 0) {
            query = createSQLQuery(sqlColumn + sqlCondition);
            if (companyId != null)
                query.setInteger("company_id", companyId);
            if (supplierId != null)
                query.setInteger("supplier_id", supplierId);
            if (code != null)
                query.setString("code", "%" + code + "%");
            result = query.setFirstResult(start).setMaxResults(limit).list();
        }
        Page<Object[]> page = new Page<Object[]>();
        page.setTotalCount(total);
        if (result != null && !result.isEmpty())
            page.setResult(result);
        return page;
    }

    public void saveSupplierMapping(Integer companyId, Integer supplierId, String code) {
        String sql = "insert into t_jiuqi_supplier_mapping values(?,?,?,'',1)";
        createSQLQuery(sql, companyId, supplierId, code).executeUpdate();
    }

    public void deleteSupplierMapping(Integer companyId, Integer supplierId) {
        String sql = "delete from t_jiuqi_supplier_mapping where company_id=? and supplier_id=?";
        createSQLQuery(sql, companyId, supplierId).executeUpdate();
    }
}
